﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate;
using NHibernate.Linq;
using NHibernate.Criterion;

using Hasiu.Entity;

namespace Hasiu.Service
{
    public class ProductService
    {
        public static readonly ProductService _ = new ProductService();

        private ISession Session { get; set; }

        public ProductService()
        {
            Session = NHibernateHelper.GetCurrentSession();
        }

        public void Save(Product product)
        {
            Session.Clear();
            Session.Save(product);
            Session.Flush();
        }

        public void Update(Product product)
        {
            Session.Clear();
            Session.Update(product);
            Session.Flush();
        }

        public void Delete(params string[] id)
        {
            Session.Clear();
            var query = Session.Query<Product>().Where(o => id.Contains(o.Id));
            foreach (var v in query)
            {
                Session.Delete(v);
            }
            Session.Flush();
        }

        public Product Get(string id)
        {
            return Session.Get<Product>(id);
        }

        public IList<Product> GetList(
            int pageIndex,
            int pageSize,
            out int dataCount,
            string name,
            string productTypeId,
            DateTime? startTime,
            DateTime? endTime)
        {
            var queryCount = Session.CreateCriteria(typeof(Product));
            var queryList = Session.CreateCriteria(typeof(Product));
            if (!string.IsNullOrEmpty(name))
            {
                queryCount.Add(Restrictions.Like("Name", "%" + name + "%"));
                queryList.Add(Restrictions.Like("Name", "%" + name + "%"));
            }
            if (!string.IsNullOrEmpty(productTypeId))
            {
                queryCount.Add(Restrictions.Eq("ProductTypeId", productTypeId));
                queryList.Add(Restrictions.Eq("ProductTypeId", productTypeId));
            }
            if (startTime != null)
            {
                queryCount.Add(Restrictions.Gt("AddTime", startTime));
                queryList.Add(Restrictions.Gt("AddTime", startTime));
            }
            if (endTime != null)
            {
                queryCount.Add(Restrictions.Lt("AddTime", endTime));
                queryList.Add(Restrictions.Lt("AddTime", endTime));
            }
            dataCount = Convert.ToInt32(queryCount.SetProjection(Projections.Count("Id")).UniqueResult());
            return queryList.AddOrder(new Order("AddTime", false))
                .SetFirstResult(pageIndex * pageSize)
                .SetMaxResults(pageSize)
                .List<Product>();
        }
    }
}
